﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Microsoft.Practices.Unity;
using EvidenceManagement.ViewModel.Common;
using EvidenceManagement.ViewModel.Security;
using EvidenceManagement.Logic.Security;
using EvidenceManagement.Model.Security;
using EvidenceManagement.PresentationModel.Common;

namespace EvidenceManagement.PresentationModel.Security
{
    public class LogOnPresenter : ILogOnPresenter
    {

        #region Fields

        readonly ILogOnView logOnView;
        readonly IUnityContainer container = new UnityContainer();
        readonly ISystemUserManager userManager = null;

        #endregion

        #region Constructor

        private LogOnPresenter()
        { 
        }

        public LogOnPresenter(ILogOnView view)
        {
            logOnView = view;
            container.RegisterType<ISystemUserManager>();
            userManager = GetUserManager();
        }

        #endregion

        #region Private Methods

        private ISystemUserManager GetUserManager()
        {
            return container.Resolve<SystemUserManager>();
        }

        private ISystemUserManager UserManager
        {
            get
            {
                return userManager;
            }
        }

        #endregion

        #region ILogOnPresenter Members

        public void LogOn()
        {
            ISystemUser user =  UserManager.GetUser(logOnView.UserName, logOnView.Password);

            if (user != null)
            {
                (logOnView as IView).CurrentSystemUserId = user.SystemUserID;

                logOnView.LogOnPassed();
            }                
            else
            {
                logOnView.Password = string.Empty;
                logOnView.LogOnFailed();
            }
        }

        #endregion

        #region IPresenter Members

        public void OnLoad()
        {
            string @namespace = "EvidenceManagement.ViewModel";

            var q = from t in Assembly.GetExecutingAssembly().GetTypes()
                    where t.IsClass 
                    && t.Namespace.StartsWith(@namespace) 
                    && t.ReflectedType == null                    
                    select t;
            q.ToList().ForEach(t => Console.WriteLine(t.FullName));
        }

        public IView View
        {
            get { return logOnView; }
        }

        public void OnClose()
        {
            
        }

        #endregion
    }
}
